package mutilthread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description: CountDownLatch 的使用示例 (搭配线程池使用)
 * User: Li_yizYa
 * Date: 2025—04—08
 * Time: 18:59
 */
public class Demo28 {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(4);

        // 构造方法的数字，就是拆分出来的任务个数
        CountDownLatch countDownLatch = new CountDownLatch(20);
        for (int i = 0; i < 20; i++) {
            int id = i;
            executorService.submit(() -> {
                System.out.println("下载任务 " + id + " 开始执行");
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("下载任务 " + id + " 结束执行");

                // 执行完成
                countDownLatch.countDown();
            });
        }
            // 当 countDownLatch 收到了 20 个“完成”，所有的任务就都完成了
            // await => all wait
            countDownLatch.await();
            System.out.println("所有任务都完成");
    }
}
